package com.example.app_back.controller;

import com.example.app_back.Response;
import com.example.app_back.dao.Dynamics;
import com.example.app_back.dao.DynamicsRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
public class DynamicsController {
        @Autowired
        private  DynamicsRepository dynamicsRepository;

        @PostMapping("/dynamics")
        public String addNewDynamics(@RequestParam("username") String username, @RequestParam("picture") MultipartFile file  )
        {
                try {
                        System.out.println("start");
                        // 1. 保存图片到服务器
                        String filePath = saveImage(file);
                        System.out.println("start1");
                        // 2. 保存其他信息到数据库
                        Dynamics dynamics = new Dynamics();
                        dynamics.setUsername(username);
                        System.out.println(username);
                        dynamics.setPictureStorage(filePath);
                        System.out.println(filePath);
                        dynamicsRepository.save(dynamics);
                        return   "Success";
                } catch (Exception e) {
                        return "Filed";
                }

        }
        private String saveImage(MultipartFile file) throws IOException {
                // 生成唯一文件名
                String fileName = UUID.randomUUID() + "." + getExtension(file.getOriginalFilename());

                // 创建存储目录（如果不存在）
                Path uploadPath = Paths.get(System.getProperty("user.dir"), "uploads", "images");
                if (!Files.exists(uploadPath)) {
                        Files.createDirectories(uploadPath);
                }

                // 保存文件到指定路径
                Path filePath = uploadPath.resolve(fileName);
                Files.write(filePath, file.getBytes());
                System.out.println("pic");
                // 返回访问URL（需配合静态资源映射）
                return "/images/" + fileName;
        }
        public String getExtension(String filename) {
                if (filename == null || filename.lastIndexOf('.') == -1) {
                        return "";
                }
                return filename.substring(filename.lastIndexOf('.') + 1);
        }
}
